#include "user.h"
#include "keyboard.h"
#include "GPIO.h"

extern U8 key_down_flag, key_confirmed_flag, key_up_flag;
extern U8 cur_keyvalue, pre_keyvalue;

/********************************************************
get the button number
*********************************************************/
void Set_key_col_out(U8 col, U8 value)
{
	Set_GPIO_bit_output(GPIO_PB, col, value);
}

U8 Get_key_row(void)
{
	U8 value0 = 0, value1 = 0;
	value0 = Get_GPIO_group(GPIO_PC);
	value1 = ((Get_GPIO_group(GPIO_PD) >> 3 ) & 0x03 );
	return ( (value0 & 0x3f) & (value1 << 6) );	
}

U8 tick_to_confirm_key = 0;
U8 flag_to_confirm_key = 0;
/************************************************
only support one button clicked
*************************************************/
U8 scan_keyboard(void)
{
	U8 keyvalue, col, row;

	for(col = 0 ; col < 4 ; col++)
	{
		Set_key_col_out(0, 1);
		Set_key_col_out(1, 1);
		Set_key_col_out(2, 1);
		Set_key_col_out(3, 1);

		Set_key_col_out(col, 0);
		if ( (keyvalue = Get_key_row()) != 0xff )
		{
			for( row = 0 ; row < 8 ; row++ )
			{
				if( ! (keyvalue & (0x01 << row)))
				{
					key_down_flag = 1;
					tick_to_confirm_key = 10;
					return (col * 8 + row);
				}
			}
		}
	}
	return KEY_NULL;
}

void timer_to_check_key(void)
{
	if(tick_to_confirm_key > 0)
	{
		if(tick_to_confirm_key -- == 0)
		{
			flag_to_confirm_key = 1;
		}
	}
}

/******************************************************
******************************************************/
void confirm_keydown(void)
{
	if( key_down_flag && flag_to_confirm_key)
	{
		cur_keyvalue = scan_keyboard();
		if( cur_keyvalue == pre_keyvalue)
		{
			key_confirmed_flag = 1;
			key_up_flag = 0;
			key_down_flag = 1;
			tick_to_confirm_key = 10;
		}
		else
		{
			key_down_flag = 0;
		}
	}
}

void process_keydown(U8 key)
{
	key_down_flag = 0;
	key_confirmed_flag = 0;
	key_up_flag = 0;

	uart_send_key_cmd(key);
}
